import { reactive, onMounted } from 'vue'
import _ from 'lodash'

export default function useEditForm(
  proxy,
  options = {
    model: {
      idProp: 'id',
      tipsProp: undefined
    },
    view: {
      refreshView: undefined
    },
    editForm: {
      ref: 'editFormRef'
    },

    action: {
      add: {
        api: undefined,
        before: undefined,
        after: undefined,
        defaultData: undefined,
        title: '添加记录',
        tips: '添加成功',
        copy: {
          before: undefined,
          after: undefined
        }
      },
      edit: {
        api: undefined,
        before: undefined,
        after: undefined,
        defaultData: undefined,
        title: '编辑记录',
        tips: '更新成功'
      },
      submitForm: {
        before: undefined,
        after: undefined,
        resolveParam: undefined
      },
      closeForm: {
        before: undefined,
        after: undefined
      }
    }
  }
) {
  // 设置默认值(测试)
  options = _.defaultsDeep(options, {
    action: {
      add: {
        title: '添加记录',
        tips: '添加成功'
      },
      edit: {
        title: '编辑记录',
        tips: '更新成功'
      }
    }
  })

  const editForm = reactive({
    show: false,
    // add edit
    type: '',
    title: '',
    data: {},
    submitLoading: false
  })

  function handleAdd() {
    if (_.isFunction(options.action.add?.before)) {
      options.action.add.before()
    }
    editForm.type = 'add'
    editForm.title = options.action.add.title
    editForm.data = defaultAddFormData()
    if (_.isFunction(options.action.add?.after)) {
      options.action.add.after()
    }
    editForm.show = true
  }

  function handleCopyAdd(copyData) {
    if (_.isFunction(options.action.add.copy?.before)) {
      options.action.add.copy.before()
    }
    editForm.type = 'add'
    editForm.title = options.action.add.title
    editForm.data = _.merge(defaultAddFormData(), copyData)
    editForm.data[options.model.idProp] = undefined
    if (_.isFunction(options.action.add.copy?.after)) {
      options.action.add.copy.after()
    }
    editForm.show = true
  }

  function handleEdit(editData) {
    if (_.isFunction(options.action.edit?.before)) {
      options.action.edit.before()
    }
    editForm.type = 'edit'
    editForm.data = _.merge(defaultEditFormData(), editData)
    editForm.title = `${options.action.edit.title}(${editForm.data[options.model.tipsProp]
      })`
    if (_.isFunction(options.action.edit?.after)) {
      options.action.edit.after()
    }
    editForm.show = true
  }

  function handleClose() {
    if (_.isFunction(options.action.closeForm?.before)) {
      options.action.closeForm.before()
    }
    editForm.show = false
    resetForm()
    if (_.isFunction(options.action.closeForm?.after)) {
      options.action.closeForm.after()
    }
  }

  function resetForm() {
    // dialog没渲染$refs获取不到值
    proxy.$refs[options.editForm.ref]?.resetFields()

    if (editForm.type === 'add') {
      editForm.data = defaultAddFormData()
    } else if (editForm.type === 'edit') {
      editForm.data = defaultEditFormData()
    } else {
      editForm.data = {}
    }
  }

  function openForm() {
    editForm.show = true
  }

  function handleSubmit() {
    // ElMessage({
    //   message: '测试异常',
    //   type: 'error'
    // })
    // return;
    if (_.isFunction(options.action.submitForm?.before)) {
      options.action.submitForm.before()
    }
    if (Object.keys(editForm.data).length === 0) {
      // TODO 空对象警告
      console.warn(editForm.data, 'form data is empty')
      return
    }

    editForm.submitLoading = true
    proxy.$refs[options.editForm.ref].validate((valid, prop) => {
      if (!valid) {
        editForm.submitLoading = false
        console.warn(prop, 'valid failed')
        return
      }

      const param = _.isFunction(options.action.submitForm?.resolveParam)
        ? options.action.submitForm.resolveParam(editForm.data)
        : editForm.data
      // 判断新增还是更新
      if (editForm.type === 'add') {
        options.action.add
          .api(param)
          .then((res) => {
            editForm.submitLoading = false
            if (_.isFunction(options.action.submitForm?.after)) {
              options.action.submitForm.after(res)
            }
            handleClose()
            proxy.$modal.msgSuccess(options.action.add.tips)
            if (_.isFunction(options.view?.refreshView)) {
              options.view.refreshView()
            }
          })
          .catch((e) => {
            editForm.submitLoading = false
            // console.error(e, 'submit error')
          })
      } else {
        options.action.edit
          .api(param)
          .then((res) => {
            editForm.submitLoading = false
            if (_.isFunction(options.action.submitForm?.after)) {
              options.action.submitForm.after(res)
            }
            handleClose()
            proxy.$modal.msgSuccess(options.action.edit.tips)
            if (_.isFunction(options.view?.refreshView)) {
              options.view.refreshView(res)
            }
          })
          .catch((e) => {
            editForm.submitLoading = false
            // console.error(e, 'submit error')
          })
      }
    })
  }

  function defaultAddFormData() {
    return options.action.add.defaultData
      ? _.cloneDeep(options.action.add.defaultData)
      : {}
  }

  function defaultEditFormData() {
    return options.action.edit.defaultData
      ? _.cloneDeep(options.action.edit.defaultData)
      : {}
  }

  onMounted(() => {
    console.log('useEdit hook mounted!')
  })

  return {
    editForm,
    handleAdd,
    handleCopyAdd,
    handleEdit,
    handleClose,
    openForm,
    resetForm,
    handleSubmit
  }
}
